package be.wavenet.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloServlet
 */
public class HelloServlet extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloServlet()
    {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		afficherFormulaire(request, response);		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		afficherMessageBienvenue(request, response);
	}	

	private void afficherMessageBienvenue(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		PrintWriter out = response.getWriter();
		GregorianCalendar now = new GregorianCalendar();
				
		String formattedDate = getFormatedDateNow(now);
		String formattedTime = getFormatedTimeNow(now);
		String username = request.getParameter("username");
		if( username==null || username.isEmpty())
		{
			//request.getP
			username = "World";
			response.sendRedirect("https://www.google.be?#q=username "+username);
		}	
		out.println("<!DOCTYPE html><html><head><meta charset=\"ISO-8859-1\"><title>HelloWeb2</title></head>"+
		"<body><h1>Hello "+username+" : </h1><p>nous sommes le "+formattedDate+" et il est "+formattedTime+".</p></body></html>");
	}	

	private String getFormatedDateNow(GregorianCalendar now) 
	{		
		SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE dd MMMM yyyy");		
		return dateFormat.format(now.getTime());		
	}
	
	private String getFormatedTimeNow(GregorianCalendar now) 
	{	
		SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");		
		return timeFormat.format(now.getTime());		
	}
	
	private void afficherFormulaire(HttpServletRequest request, HttpServletResponse response) throws IOException
	{

		PrintWriter out = response.getWriter();
		
		out.println("<!DOCTYPE html><html><head><meta charset=\"ISO-8859-1\"><title>HelloWeb2</title></head>"+
		"<body><h1>Hello Web</h1>"+		
		"<form action=\"HelloServlet?username=2\" method=\"post\">"+
		  "Username:<input type=\"text\" name=\"username\">"+
		  "<input type=\"submit\"></form></body></html>");
		
	}
}
